package com.wgj.android.ui.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jiaai.xui.utils.http.HttpCallBack;
import com.jiaai.xui.utils.http.ListHttpCallBack;
import com.jiaai.xui.utils.http.XHttp;
import com.jiaai.xui.utils.http.entity.VUpload;
import com.jiaai.xui.view.widget.XLoadingDialog;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.R;
import com.wgj.android.entity.YoukuBean;
import com.wgj.android.http.OKHttpEngine;
import com.wgj.android.http.WGJAPI;
import com.wgj.android.utils.BitmapUtil;
import com.wgj.android.utils.CacheUtils;
import com.wgj.android.youku.Config;
import com.wgj.android.youku.IUploadResponseHandler;
import com.wgj.android.youku.YoukuUploader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

import static android.provider.MediaStore.Video.Thumbnails.MINI_KIND;

public class VideoUploadActivity extends AppCompatActivity {

    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.tv_content)
    EditText tvContent;
    @BindView(R.id.button)
    TextView button;
    @BindView(R.id.percent)
    TextView percent;
    @BindView(R.id.progress)
    RelativeLayout progress;
    private Intent intent;

    private String filPaths;

    private YoukuUploader uploader;
    private String videoID;
    private YoukuBean youkuBean;
    private Bitmap thumb;
    private String thumbUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_video_upload);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    private void initData() {

        //uploadPicture(BitmapUtil.compressImage(ThumbnailUtils.createVideoThumbnail(filPaths,MINI_KIND)));//将视频的缩略图上传

    }

    private void initView() {
        filPaths = getIntent().getStringExtra("video");
        //thumb = getIntent().getParcelableExtra("thumb");
        //请替换成自己的clientid与clientsecret
        uploader = YoukuUploader.getInstance(Config.client_id, Config.client_secret, getApplicationContext());
    }

    @OnClick(R.id.button)
    public void onClick(View v) {
        if (TextUtils.isEmpty(filPaths)) {
            XToast.error("不能为空");
            return;
        }
        if (TextUtils.isEmpty(tvContent.getText().toString())) {
            XToast.error("不能为空");
            return;
        }
        if (TextUtils.isEmpty(etTitle.getText().toString())) {
            XToast.error("不能为空");
            return;
        }

        //uploadPicture(BitmapUtil.compressImage(thumb));//将视频的缩略图上传
        uploadPicture(BitmapUtil.compressImage(ThumbnailUtils.createVideoThumbnail(filPaths,MINI_KIND)));//将视频的缩略图上传
        upload();
    }

    private void uploadPicture(File file) {

        Map<String, File> params = new HashMap<>();
        params.put("thumb", file);
        XHttp.obtain().upload("picture", params, new ListHttpCallBack<VUpload>() {
            @Override
            public void onSuccess(List<VUpload> list) {
                thumbUrl = list.get(0).getFilePath();


            }

            @Override
            public void onFailed(int i, String s, boolean b) {

            }
        });
    }

    private void upload() {
        final HashMap<String, String> params = new HashMap<String, String>();
        //access_token可以在http://cloud.youku.com/tools的手动获取选项卡获取
        params.put("access_token", CacheUtils.getYouKuToken());
        HashMap<String, String> uploadInfo = new HashMap<String, String>();
        uploadInfo.put("title", "旺旺通");
        uploadInfo.put("tags", "视频");
        uploadInfo.put("file_name", filPaths);
        uploader.upload(params, uploadInfo, new IUploadResponseHandler() {
            @Override
            public void onStart() {
                button.setClickable(false);
                button.setText("上传中");
                progress.setVisibility(View.VISIBLE);
                percent.setText("等待中");
            }

            @Override
            public void onSuccess(JSONObject response) {
                try {
                    videoID = response.getString("video_id");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                getVideo();
            }

            @Override
            public void onProgressUpdate(int counter) {
                percent.setText(counter+"%");
            }

            @Override
            public void onFailure(JSONObject errorResponse) {
                //token过期就刷新
                try {
                    JSONObject js =errorResponse.getJSONObject("error");
                    int code =js.getInt("code");
                    if(code==1008||code==1007||code==1009||code==1012){
                        getToken();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


                progress.setVisibility(View.GONE);
            }

            @Override
            public void onFinished() {
                button.setText("上传");
                progress.setVisibility(View.GONE);
                button.setClickable(true);
            }
        });
    }

    //上传视频信息到服务器
    private void showUploadVideoDialog() {
        Map<String, Object> params = new HashMap<>();
        params.put("type", 4);
        params.put("addressHttp", youkuBean.getLink());
        params.put("thumbnail", (youkuBean.getThumbnail() == null) ? thumbUrl : youkuBean.getThumbnail());
        params.put("title", etTitle.getText().toString());
        params.put("introduce", tvContent.getText().toString());
        params.put("member", CacheUtils.getMember().getM_id());
        params.put("resourceId", videoID);
        XHttp.obtain().post(WGJAPI.UPLOAD_VIDEO_URL, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String str) {
                XToast.success("上传成功");

                finish();
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                XToast.error("上传失败");

            }
        });
    }

    //访问优酷api获得视频信息 上传到自己的服务器
    private void getVideo() {
        Request request = new Request.Builder().url("https://api.youku.com/videos/show.json?client_id=" + Config.client_id + "&video_id=" + videoID).build();
        new OKHttpEngine().client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                XToast.error("异常");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                com.alibaba.fastjson.JSONObject restResult = JSON.parseObject(response.body().string());
                youkuBean = new Gson().fromJson(restResult.toJSONString(), YoukuBean.class);
                showUploadVideoDialog();

            }
        });
    }
    private void getToken(){
        XHttp.obtain().get(WGJAPI.BASEURL + "youku/token", null, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                CacheUtils.cacheYouKuToken(s);
                button.setClickable(true);
                button.setText("上传");
                XToast.info("请点击重试",2000);
            }

            @Override
            public void onFailed(int i, String s, boolean b) {
                button.setClickable(true);
                button.setText("上传");
                XToast.error("刷新token失败");
            }
        });
    }
}
